package ru.gelin.android.bells;

import static ru.gelin.android.bells.Utils.isTomorrow;

import java.util.Calendar;
import java.util.Date;

import ru.gelin.android.bells.timers.Timer;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TimePicker.OnTimeChangedListener;

public class SaveTimerActivity extends NowActivity implements Constants {

    /** Key in the instance state bundle to save selected ringtone */
    static final String SELECTED_RINGTONE_KEY = "selectedRingtone";
    /** Key in the instance state bundle to save initial timer start time */
    static final String INITIAL_START_KEY = "initialStart";

    /** Storage of the timers */
    protected TimerStorage timers;
    /** Ringtone manager */
    protected RingtoneManager ringtoneManager;
    /** Previously selected alarm ringtone */
    protected int selectedRingtone = 0;     //first in the list
    /** Original start time of the edited timer */
    protected Date initialStart;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            initialStart = now;
        } else {
            initialStart = new Date(
                    savedInstanceState.getLong(INITIAL_START_KEY, System.currentTimeMillis()));
        }

        setContentView(R.layout.timer);
        timers = TimerStorage.getInstance(this);
        
        TimePicker start = (TimePicker)findViewById(R.id.timer_start);
        start.setIs24HourView(true);
        start.setOnTimeChangedListener(new OnTimeChangedListener() {
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                updateAlarmTime();
            }
        });
        
        TimePicker period = (TimePicker)findViewById(R.id.timer_period);
        period.setIs24HourView(true);
        period.setOnTimeChangedListener(new OnTimeChangedListener() {
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                updateAlarmTime();
            }
        });
        
        Spinner alarm = (Spinner)findViewById(R.id.timer_alarm);
        ringtoneManager = new RingtoneManager(this);
        ringtoneManager.setType(RingtoneManager.TYPE_ALARM);
        ringtoneManager.setStopPreviousRingtone(true);
        
        Cursor cursor = ringtoneManager.getCursor();
        //DatabaseUtils.dumpCursor(cursor);
        SpinnerAdapter adapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_spinner_item, cursor, 
                new String[] {cursor.getColumnName(RingtoneManager.TITLE_COLUMN_INDEX)},
                new int[] {android.R.id.text1});
        alarm.setAdapter(adapter);
        
        setVolumeControlStream(AudioManager.STREAM_ALARM);
    }
    
    @Override
    public void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        
        if (savedInstanceState != null) {
            selectedRingtone = savedInstanceState.getInt(SELECTED_RINGTONE_KEY, selectedRingtone);
        }
        
        Spinner alarm = (Spinner)findViewById(R.id.timer_alarm);
        alarm.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                if (position != selectedRingtone) {     //another ringtone is selected
                    ringtoneManager.getRingtone(position).play();
                }
                selectedRingtone = position;
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                //nothing to do
            }
        });
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(SELECTED_RINGTONE_KEY, selectedRingtone);
        outState.putLong(INITIAL_START_KEY, initialStart.getTime());
    }
    
    @Override
    public void onPause() {
        super.onPause();
        ringtoneManager.stopPreviousRingtone();
    }
    
    /**
     *  Converts entered hour and minute to date.
     *  Tries to avoid this situation:
     *  current time is 23:50, entered time is 00:10.
     *  The date should always be in the future 
     *  (relative to the startTime of the timer during the activity creation).
     */
    protected Date toDate(int hour, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        Date timer = calendar.getTime();
        Date boundary = initialStart.before(now) ? initialStart : now;
        if (timer.before(boundary)) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            return calendar.getTime();
        } else {
            return timer;
        }
    }
    
    protected void updateAlarmTime() {
        Timer timer = new Timer();
        TimePicker start = (TimePicker)findViewById(R.id.timer_start);
        TimePicker period = (TimePicker)findViewById(R.id.timer_period);
        timer.setStartTime(toDate(start.getCurrentHour(), start.getCurrentMinute()));
        timer.setPeriod(period.getCurrentHour(), period.getCurrentMinute());
        timer.normalize(now);
        TextView nextStart = (TextView)findViewById(R.id.timer_next_start);
        Date alarmTime = timer.getAlarmTime(now);
        nextStart.setText(getResources().getString(
                isTomorrow(now, alarmTime) ? 
                        R.string.timer_alarm_time_tomorrow : R.string.timer_alarm_time, 
                alarmTime));
    }

    protected void saveTimer(Timer timer) {
        CheckBox enabled = (CheckBox)findViewById(R.id.timer_enabled);
        timer.setEnabled(enabled.isChecked());
        
        TimePicker start = (TimePicker)findViewById(R.id.timer_start);
        timer.setStartTime(toDate(start.getCurrentHour(), start.getCurrentMinute()));
        
        TimePicker period = (TimePicker)findViewById(R.id.timer_period);
        timer.setPeriod(period.getCurrentHour(), period.getCurrentMinute());
        
        TextView message = (TextView)findViewById(R.id.timer_message); 
        timer.setMessage(String.valueOf(message.getText()));
        
        Spinner alarm = (Spinner)findViewById(R.id.timer_alarm);
        Uri ringtoneUri = ringtoneManager.getRingtoneUri(alarm.getSelectedItemPosition());
        Log.d(TAG, "alarm sound: " + ringtoneUri);
        timer.setAlarm(String.valueOf(ringtoneUri));
        
        timer.normalize(now);
        if (timer.getId() == 0) {
            timers.insert(timer);
        } else {
            timers.update(timer);
        }
        timers.save();
        finish();
    }

}